package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.constants.AdminConstants;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.AuthorFeign;
import com.usian.user.feign.MediaFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.ApUserRealnameMapper;
import com.usian.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.LinkedHashMap;

@Service
public class ApUserRealnameServiceImpl extends BaseServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private MediaFeign mediaFeign;

    @Autowired
    private AuthorFeign authorFeign;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //判断状态 非0，1，2，9返回错误信息
        if (dto == null || (dto.getStatus() != null && (dto.getStatus() != 0 && dto.getStatus() != 1 && dto.getStatus() != 2 && dto.getStatus() != 9)))
            return paramError;
        //判断状态 为空查询未审核的
        LambdaQueryWrapper<ApUserRealname> eq = Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getStatus, dto.getStatus() != null ? dto.getStatus() : 1);
        return getPageResult(dto, eq);
    }


    @Override
    //分布式事务
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto) {
        //判断对象 状态 id为空返回错误信息
        if (dto == null || dto.getStatus() == null || dto.getId() == null) return paramError;
        if (dto.getStatus() != AdminConstants.FAIL_AUTH && dto.getStatus() != AdminConstants.PASS_AUTH)
            return paramError;
        //根据操作行为修改认证表中的状态 根据id查询认证表的信息
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null) return noData;
        //给状态赋值
        userRealname.setStatus(dto.getStatus());
        //判断原因是否为空 为空给认证表赋值
        if (StringUtils.isNotEmpty(dto.getMsg())) userRealname.setReason(dto.getMsg());
        //修改认证表的信息
        updateById(userRealname);
        //判断状态是否为9
        if (dto.getStatus() == AdminConstants.PASS_AUTH) {
            //根据认证id查询用户id，更新用户flag
            ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
            if (apUser == null) return noData;
            apUser.setFlag((short) 1);
            //修改用户表
            apUserMapper.updateById(apUser);
            //向自媒体用户表同步自媒体人 远程调用根据名字查询
            WmUser wmUser = mediaFeign.findByName(apUser.getName());
            if (wmUser == null) {
                wmUser = new WmUser();
                try {
                    //名字不存在添加数据（复制）
                    BeanUtils.copyProperties(wmUser, apUser);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                //属性赋值
                wmUser.setApUserId(apUser.getId());
                wmUser.setStatus(9);
                wmUser.setType(1);
                wmUser.setLoginTime(new Date());
                wmUser.setCreatedTime(new Date());
                //远程调用添加用户信息到自媒体表
                ResponseResult result = mediaFeign.save(wmUser);
                Object data = result.getData();
                //添加封装自媒体信息 返回自媒体的id
                Integer id = (Integer) ((LinkedHashMap) data).get("id");
                //给自媒体表的主键赋值
                wmUser.setId(id);
            }
            //同步作者信息 根据用户id查询作者表
            ApAuthor author = authorFeign.findByUserId(apUser.getId());
            if (author == null) {
                author = new ApAuthor();
                author.setName(apUser.getName());
                author.setType(2);
                author.setUserId(apUser.getId());
                author.setCreatedTime(new Date());
                author.setWmUserId(wmUser.getId());
                //远程调用添加信息到作者表
                ResponseResult save = authorFeign.save(author);
                LinkedHashMap map = (LinkedHashMap) save.getData();
                //添加返回作者表的id 然后赋值给自媒体
                wmUser.setApAuthorId((Integer) (map.get("id")));
                //wmUser.setApAuthorId(((ApAuthor) save.getData()).getId());
                //更新自媒体人表中的作者id
                mediaFeign.updateAuthorId(wmUser);
            }
            //int i=1/0; 回滚测试
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, "认证成功");
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, "认证失败");
        }
    }
}
